package com.example.adouble.cehuamenu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.adouble.cehuamenu.R;
import com.example.adouble.cehuamenu.mode.Book;
import com.example.adouble.cehuamenu.sqlite.MySQLiteOpenHelper;
import com.example.adouble.cehuamenu.ui.adapter.SearchAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * 搜索
 */

public class SearchActivity extends AppCompatActivity {

    private TextView clear,tv_tip;
    private ListView lv_history;
    private EditText search;
    private MySQLiteOpenHelper helper = new MySQLiteOpenHelper(this);
    private BaseAdapter adapter;
    private SQLiteDatabase db;
    private RecyclerView sv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        // 初始化控件
        initView();

        // 清空搜索历史
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                queryData("");
            }
        });

        // 搜索框的键盘搜索键点击回调
        search.setOnKeyListener(new View.OnKeyListener() {

            // 输入完后按键盘上的搜索键
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = hasData(search.getText().toString().trim());
                    if (!hasData) {
                        insertData(search.getText().toString().trim());
                        queryData("");
                    }
                    // TODO 搜索图书
                    allBk();

                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 0) {
                    tv_tip.setText("搜索历史");
                } else {
                    tv_tip.setText("搜索结果");
                }
                String tempName = search.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据
                queryData(tempName);

            }
        });

        lv_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                search.setText(name);
                allBk();

            }
        });

        // 第一次进入查询所有的历史记录
        queryData("");
    }

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into history(name) values('" + tempName + "')");
        db.close();
    }

    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from history where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
                new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        lv_history.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from history where name = ?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from history");
        db.close();
    }

    private void initView() {
        search = (EditText) findViewById(R.id.search);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        lv_history = findViewById(R.id.lv_history);
        clear = (TextView) findViewById(R.id.clear);
        sv = findViewById(R.id.bksearch);

    }

    public void back(View view){
        Intent intent = new Intent(SearchActivity.this,MainActivity.class);
        startActivity(intent);
        finish();
    }
    /*
    *本地模糊查询
     */
    public List<Book> getBook(List<Book> list, String bkname){
        List<Book> l = new ArrayList<>();
        for(Book i:list){
            if(i.getB_name().contains(bkname)){
                l.add(i);
            }
        }
        return l;
    }

    /*
    *搜索图书
     */
    public void allBk(){
        final String bkname = search.getText().toString();
        BmobQuery<Book> bookBmobQuery = new BmobQuery<>();
        String bql = "select * from Book";
        bookBmobQuery.doSQLQuery(bql, new SQLQueryListener<Book>() {
            @Override
            public void done(BmobQueryResult<Book> result, BmobException e) {
                if(e == null){
                    final List<Book> li = getBook(result.getResults(),bkname);
                    if(li.size() > 0){
                        sv.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
                        SearchAdapter adapter = new SearchAdapter(SearchActivity.this,li);
                        sv.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        adapter.setItemOnClickListener(new SearchAdapter.ItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Intent intent = new Intent(SearchActivity.this,DetailActivity.class);
                                intent.putExtra("bname",li.get(position).getB_name());
                                startActivity(intent);
                            }
                        });
                    }
                }
            }
        });
    }
}
